package dk.itu.samd.group2.tagapastry.messages;

import java.util.ConcurrentModificationException;
import dk.itu.samd.group2.tagapastry.Index;
import dk.itu.samd.group2.tagapastry.IndexEntry;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagFactory;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;
import rice.environment.logging.Logger;
import rice.p2p.commonapi.Id;
import rice.p2p.commonapi.NodeHandle;

public class MaintenanceMsg extends TagapastryMsg {

	public static final int TYPE = 9;
	private static final long serialVersionUID = TYPE;
	
	public MaintenanceMsg(NodeHandle sender) {
		super(null, sender, sender);
	}
	
	@Override
	public void execute(TagapastryImpl taga) {
		//System.out.println("executing on " + taga.getNode().getId());
		try {
			for (Index index : taga) {
//				System.out.println("  " + index);
//				for (IndexEntry entry : index) {
//					System.out.println("    " + entry);
//				}
				if(taga.getLoger().level <= Logger.FINEST) {
					taga.getLoger().log(tag + "  size: " + index.getSize() + "  delta: " + index.getDelta());
					for (IndexEntry entry : index.getEntries()) {
						taga.getLoger().log("  " + entry);
					}
				}
				if (index.isRoot()) {
					continue;
				}
				//Index index = indexes.get(tag);
				if (index.isDeltaChanged()) {
					// Tag should be get from index, otherwise we query against null
					tag = index.getTag();
					Tag parentTag = TagFactory.duplicateTagMinusExtension(tag);
					UpdateSizeMsg msg = new UpdateSizeMsg(parentTag, taga.getNodeHandle(), index.getDelta());
					taga.send(msg);
					index.resetDelta();
				} 
			}
		} catch (ConcurrentModificationException e) {
			// WATCH OUT OVER HERE WHEN DEBUGGING AT NIGHT
			// we don't want to have infinite loop which may happen
			return;
		}
		
	}

	@Override
	public Id getRecepientId() {
		return originalSender.getId();
	}

	@Override
	public short getType() {
		return TYPE;
	}
	
	public String toString() {
		return super.toString() + " }";
	}

}
